<?php
namespace App\Services;

use App\Models\MaterielClassModel;
use App\Models\MaterielTypeModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MaterielClassService
{
    //分类列表
    static public function index($parentId, $data)
    {
        $condition = [];
        $condition1 = [];
        if(!empty($data['materiel_class_id'])) {
            $condition['b.id'] = ['EQ' => $data['materiel_class_id']];
            $condition1['materiel_class_id'] = ['EQ' => $data['materiel_class_id']];
        }

        $keyword = empty($data['keyword'])?'':$data['keyword'];

        if(!empty($condition) || $keyword != '') {
            $result = SELF::withSearch($parentId, $data, $condition, $condition1, $keyword);
        }
        else {
            $result = SELF::withoutSearch($parentId, $data);
        }

        return $result;
    }

    static public function withSearch($parentId, $data, $condition, $condition1, $keyword)
    {
        $typeInfo = MaterielClassModel::getMaterielAndClassInfo($parentId, $condition, $keyword, $data);

        $firstClass = [];
        $secondClass = [];
        foreach($typeInfo as $k => $v) {
            $firstClass[] = $v['f_id'];
            $secondClass[] = $v['s_id'];
        }

        return MaterielClassModel::select(
                                    'id',
                                    'class_name',
                                    'class_no',
                                )
                                ->from('materiel_class')
                                ->where('main_id', $parentId)
                                ->with('hasManyClass', function($query) use ($secondClass, $condition1, $keyword) {
                                    $query->select(
                                        'id',
                                        'class_name',
                                        'class_no',
                                        'parent_id'
                                    )
                                    ->where('delete_flag', 0)
                                    ->with('hasManyType', function($query) use ($condition1, $keyword) {
                                        $query->select(
                                            'id',
                                            'materiel_name',
                                            'type_name',
                                            'materiel_img',
                                            'materiel_no',
                                            'materiel_class_id',
                                            'remark'
                                        )
                                        ->where($condition1)
                                        ->where(function($query) use ($keyword) {
                                            $query->where('materiel_name', 'LIKE', '%'.$keyword.'%');
                                            $query->orWhere('type_name', 'LIKE', '%'.$keyword.'%');
                                            $query->orWhere('materiel_no', 'LIKE', '%'.$keyword.'%');
                                        })
                                        ->where('delete_flag', 0);
                                    })
                                    ->whereIn('id', array_unique($secondClass));
                                })
                                ->where('parent_id', 0)
                                ->where('delete_flag', 0)
                                ->whereIn('id', array_unique($firstClass))
                                ->orderBy('id', 'asc')
                                ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
    }

    static public function withoutSearch($parentId, $data)
    {
        $info = MaterielClassModel::select(
                                    'id',
                                    'class_name',
                                    'class_no',
                                )
                                ->from('materiel_class')
                                ->where('main_id', $parentId)
                                ->with('hasManyClass', function($query) {
                                    $query->select(
                                        'id',
                                        'class_name',
                                        'class_no',
                                        'parent_id'
                                    )
                                    ->where('delete_flag', 0)
                                    ->with('hasManyType', function($query) {
                                        $query->select(
                                            'id',
                                            'materiel_name',
                                            'type_name',
                                            'materiel_img',
                                            'materiel_no',
                                            'materiel_class_id',
                                            'remark'
                                        )
                                        ->where('delete_flag', 0);
                                    });
                                })
                                ->where('parent_id', 0)
                                ->where('delete_flag', 0)
                                ->orderBy('id', 'asc')
                                ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        return $info;
    }

    //物料分类-下拉
    static public function select($parentId)
    {
        //一级分类信息
        $firstClass = MaterielClassModel::getMaterielFirstClass($parentId);

        $firstIdArr = [];
        foreach($firstClass as $value) {
            $firstIdArr[] = $value['id'];
        }

        //二级分类信息
        $secondClass = MaterielClassModel::getMaterielSecondClass($firstIdArr);

        foreach($firstClass as $key => $value) {
            foreach($secondClass as $k => $val) {
                if($value['id'] == $val['parent_id']) {
                    // unset($val['parent_id']);
                    $firstClass[$key]['class_info'][] = $val;
                }
            }

            //未匹配到二级分类
            if(empty($firstClass[$key]['class_info'])) {
                $firstClass[$key]['class_info'] = [];
            }
        }

        return $firstClass;
    }

    //新建物料分类
    static public function add($parentId, $userId, $data)
    {
        $data['parent_id'] = !$data['type']?0:$data['parent_id'];
        $data['created_at'] = time();
        $data['main_id'] = $parentId;

        //type->0:一级分类;1:二级分类;
        if($data['type']) {
            if($data['parent_id'] == 0) {
                return ['code' => 1, 'msg' => '请选择一级商品分类'];
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_no' => $data['class_no'],
                'main_id' => $parentId,
                'delete_flag' => 0
            ])->first();

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_name' => $data['class_name'],
                'main_id' => $parentId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }
        else {
            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_no' => $data['class_no'],
                'main_id' => $parentId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_name' => $data['class_name'],
                'main_id' => $parentId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }

        unset($data['type']);

        $insertId = MaterielClassModel::insertGetId($data);
        return ['code' => 0, 'data' => $insertId];
    }

     static public function del($data)
     {
         $arr = array_filter(explode(',', $data['id']), function($v) { return $v !== '';});

         $materielClassInfo = MaterielClassModel::where('delete_flag', 0)->whereIn('id', $arr)->get()->toArray();

         $firstLevel = [];
         $secondLevel = [];
         foreach($materielClassInfo as $value) {
             if($value['parent_id'] == 0) {
                 $firstLevel[] = $value['id'];
             }
             else {
                 $secondLevel[] = $value['id'];
             }
         }

         if(!empty($firstLevel)) {
             //验证二级分类是否清空
             $secondLevelInfo = MaterielClassModel::select(
                 'a.class_name',
                 'b.class_name as second_class_name'
             )
                 ->from('materiel_class as a')
                 ->leftJoin('materiel_class as b', 'a.id', '=', 'b.parent_id')
                 ->where('b.delete_flag', 0)
                 ->whereIn('b.parent_id', $firstLevel)
                 ->first();

             if(!empty($secondLevelInfo)) {
                 return [
                     'code' => 1,
                     'msg' => '分类:'.$secondLevelInfo['class_name'].'中存在未删除的二级分类:'.$secondLevelInfo['second_class_name'].'请删除后再试',
                     'data' => ''
                 ];
             }

             MaterielClassModel::whereIn('id', $firstLevel)->update(['delete_flag' => 1]);
         }

         if(!empty($secondLevel)) {
             //获取二级分类下信息
             $materielTypeInfo = MaterielTypeModel::select(
                 'a.materiel_name',
                 'a.type_name',
                 'b.class_name'
             )
                 ->from('materiel_type as a')
                 ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                 ->where('a.delete_flag', 0)
                 ->whereIn('a.materiel_class_id', $secondLevel)
                 ->first();

             if(!empty($materielTypeInfo)) {
                 return [
                     'code' => 1,
                     'msg' => '分类:'.$materielTypeInfo['class_name'].'中存在未删除的商品:'.$materielTypeInfo['materiel_name'].'-'.$materielTypeInfo['type_name'].'请删除后再试',
                     'data' => ''
                 ];
             }

             MaterielClassModel::whereIn('id', $secondLevel)->update(['delete_flag' => 1]);
         }

         return ['code' => 0, 'msg' => 'success', 'data' => ''];
     }

    //删除指定分类，作废时间：202202231007
    static public function oldDel($data)
    {
        $checkInfo = MaterielClassModel::where('id', $data['id'])->where('delete_flag', 0)->first();

        if(empty($checkInfo)) {
            return ['code' => 1, 'msg' => '您要删除的分类不存在，请重试'];
        }

        //type:0->一级分类;1->二级分类
        if(!$data['type']) {
            $info = MaterielClassModel::where('parent_id', $data['id'])->where('delete_flag', 0)->first();

            if(!empty($info)) {
                return ['code' => 1, 'msg' => '若需要删除该一级分类，请先删除其所有的二级分类'];
            }
        }
        else {
            $info = MaterielTypeModel::where('materiel_class_id', $data['id'])->where('delete_flag', 0)->first();

            if(!empty($info)) {
                return ['code' => 1, 'msg' => '若需要删除该二级分类，请先删除其所有的物料类型', 'data' => ''];
            }
        }

        MaterielClassModel::where('id', $data['id'])->update(['delete_flag' => 1]);
        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    static public function edit($parentId, $data)
    {
        $info = MaterielClassModel::where('id', $data['id'])->first();

        $data['parent_id'] = !$data['type']?0:$data['parent_id'];
        $data['created_at'] = time();
        $data['main_id'] = $parentId;

        //type->0:一级分类;1:二级分类;
        if($data['type']) {
            if($info['parent_id'] == 0) {
                return ['code' => 1, 'msg' => '操作的数据不合法，请重试'];
            }

            if($data['parent_id'] == 0) {
                return ['code' => 1, 'msg' => '请选择一级商品分类'];
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' => $data['parent_id'],
                'class_no' => $data['class_no'],
                'main_id' => $parentId,
                'delete_flag' => 0,
            ])
            ->where('id', '!=', $data['id'])
            ->first();

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_name' => $data['class_name'],
                'main_id' => $parentId,
                'delete_flag' => 0
            ])
            ->where('id', '!=', $data['id'])
            ->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }
        else {
            if($info['parent_id'] != 0) {
                return ['code' => 1, 'msg' => '操作的数据不合法，请重试'];
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_no' => $data['class_no'],
                'main_id' => $parentId,
                'delete_flag' => 0,
            ])
            ->where('id', '!=', $data['id'])
            ->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_name' => $data['class_name'],
                'main_id' => $parentId,
                'delete_flag' => 0,
            ])
            ->where('id', '!=', $data['id'])
            ->first();

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }

        unset($data['type']);

        MaterielClassModel::where('id', $data['id'])->update($data);
        return ['code' => 0, 'data' => ''];
    }
}
